const bodyPasrer = require('body-parser')
const { list } = require('./mock')
const telList = [{
	tel: '13111111111',
	tag: [{
		name: '数码'
	}, {
		name: '镁铝'
	}, {
		name: '美女'
	}, {
		name: '电视'
	}]
}, {
	tel: '14523423234',
	tag: [{
		name: '衣服'
	}, {
		name: '直播'
	}, {
		name: '游戏'
	}, {
		name: '写代码'
	}]
}]
let telCode = null

module.exports = app => {
	app.use(bodyPasrer.json())

	app.post('/tel/code', (req, res) => {
		const { tel } = req.body
		const curr = telList.find(v => v.tel === tel);

		if (curr) {
			telCode = Math.random().toString(36).slice(2, 6)
			res.send({
				code: 200,
				telCode
			})
		} else {
			res.send({
				code: 404,
				mess: '该手机号尚未注册， 请注册！！！'
			})
		}
	})
	app.post('/login', (req, res) => {
		const { tel, code } = req.body;

		const curr = telList.find(v => v.tel === tel && code === telCode)

		if (curr) {
			res.send({
				code: 200,
				data: curr,
				token: Math.random().toString().slice(2)
			})
		} else {
			res.send({
				code: 401,
				data: '验证码不正确!!!!'
			})
		}
	})

	app.get('/api/tags/all', (req, res) => {
		res.send({
			code: 200,
			data: [{
				name: '数码'
			}, {
				name: '镁铝'
			}, {
				name: '美女'
			}, {
				name: '电视'
			}, {
				name: '衣服'
			}, {
				name: '直播'
			}, {
				name: '游戏'
			}, {
				name: '写代码'
			}]
		})
	})


	app.get('/api/list', (req, res) => {
		const { pageSize, pageCode  } = req.query

		if (pageSize * pageCode > list.length || pageCode <= 0) {
			res.send({
				code: 300,
				data: null,
				mess: '没有更多数据了！！！！'
			})
		} else {
			res.send({
				code: 200,
				data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize)
			})
		}
	})
}